import { defineStore } from 'pinia'
import { cloneDeep } from 'lodash-es'
import { CACHE_KEY, useCache } from '@/hooks/basic/useCache'
import { flatMultiLevelRoutes, generateRoute } from '@/utils/business/routerHelper'
import { remainingRouter } from '@/router/routes'
import { store } from '../index'

const { wsCache } = useCache()

export interface PermissionState {
  routers: AppRouteRecordRaw[]
  addRouters: AppRouteRecordRaw[]
}

export const usePermissionStore = defineStore('permission', {
  state: (): PermissionState => ({
    routers: [],
    addRouters: []
  }),
  getters: {
    getRouters(): AppRouteRecordRaw[] {
      return this.routers
    },
    getAdminRouters(): AppRouteRecordRaw[] {
      return (this.routers.find(el => el.path === '/admin') || {}).children || []
    },
    getAddRouters(): AppRouteRecordRaw[] {
      return flatMultiLevelRoutes(cloneDeep(this.addRouters))
    }
  },
  actions: {
    async generateRoutes(): Promise<unknown> {
      return new Promise<void>((resolve) => {
        // 获得菜单列表，它在登录的时候，setUserInfoAction 方法中已经进行获取
        let res: AppCustomRouteRecordRaw[] = []
        if (wsCache.get(CACHE_KEY.ROLE_ROUTERS)) {
          res = wsCache.get(CACHE_KEY.ROLE_ROUTERS) as AppCustomRouteRecordRaw[]
        }
        const routerMap: AppRouteRecordRaw[] = generateRoute(res)
        // 动态路由，404一定要放到最后面
        this.addRouters = routerMap.concat([
          // {
          //   path: '/:path(.*)*',
          //   redirect: '/404',
          //   name: '404Page',
          //   meta: {
          //     hidden: true,
          //   }
          // }
        ])
        // 渲染菜单的所有路由
        this.routers = cloneDeep(remainingRouter).concat(routerMap)
        resolve()
      })
    }
  }
})

export const usePermissionStoreWithOut = () => {
  return usePermissionStore(store)
}
